import pandas as pd
import logging
import similarity_service as ss


logging.basicConfig(level=logging.INFO)


# 固定参数
zl_code = 'zlcode'  
zl_name = 'zlname'  
third_code = 'thirdcode'
third_name = 'thirdname'



def match_excel_data(input_file,output_file,zl_sheet,third_sheet):
    logging.info('---------开始匹配---------')

    # 读取Excel表格
    zl_df = pd.read_excel(input_file,sheet_name=zl_sheet,engine="openpyxl")
    third_df = pd.read_excel(input_file,sheet_name=third_sheet,engine="openpyxl")

    # 提取指定列的数据
    if zl_df.empty:
        logging.error("需要对码数据为空!")
        return
    
    if third_df.empty:
        logging.error("原始字典数据为空!")
        return

    zlData = zl_df.loc[:,[zl_code,zl_name]]
    thirdData = third_df.loc[:,[third_code,third_name]]

    zl_code_arr = []
    zl_name_arr = []
    third_code_arr = []
    third_name_arr = []
    score_arr = []
    for row in zlData.values:
        res = ss.word_similarity(row[1],thirdData.values)
        # 判断相似度低于0.8后进行反转并比较
        if res[0] < 0.8:
            res_reverse = ss.word_similarity_reverse(row[1],thirdData.values)
            if res_reverse[0] > 0.8:
                res = res_reverse

        zl_code_arr.append(row[0])
        zl_name_arr.append(row[1])
        third_code_arr.append(res[1][0])
        third_name_arr.append(res[1][1])
        score_arr.append(res[0])

    matched_data = {zl_code:zl_code_arr,
                    zl_name:zl_name_arr,
                    third_code:third_code_arr,
                    third_name:third_name_arr,
                    '匹配度':score_arr}

    # 创建新的DataFrame对象来保存匹配结果
    result_df = pd.DataFrame(matched_data)

    # 将结果保存到Excel表格
    result_df.to_excel(output_file, index=False)
    print("匹配结果已保存到Excel表格:", output_file)

    logging.info('---------结束匹配---------')

